﻿// Enable the visual refresh, google maps' new look
google.maps.visualRefresh = true;

function TrackerMap() {
	var infoArr = [];
	var mapPanel = new Ext.ux.GMapPanel({
			xtype : 'gmappanel',
			id : 'my-map',
			gmapType : 'map',
			zoomLevel : 15,
			region : 'center',
			setCenter : {
				lat : 10.788202,
				lng : 106.703228

			},
			listeners : {
				mapready : handleMapReady,
				resize : function () {
					//console.log('resize  map _init');
				}
			}
		});
	var findLocationMarker  = new google.maps.Marker({
					position : createPoint(0,0),
					icon : ROOT_IMG_URL + "red.png"
				});
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();
	function handleMapReady() {};
	
	//Add device to map and panto device position
	function addTrackerMarker(info) {
		addMarker(info);
		panTo(info.getPosition());
	};
	
	//Add multip device to map
	function addMultipTrackerMarker(lstInfo) {
		for(var i=0, len = lstInfo.length; i<len; i++){
			addMarker(lstInfo[i]);		
			//console.log('add '+lstInfo[i].deviceid);
		}
	};
	function removeAllTracker(){
		for(var i=0, len = infoArr.length; i<len; i++){
			infoArr[i].marker.setMap(null);
		}
		infoArr = [];
	};
	//Add device to map 
	function addMarker(info){
		// Check device is added
		for(var i=0, len = infoArr.length; i<len; i++){
			if(info.deviceid == infoArr[i].deviceid){				
				return;
			}
		}
		
		// Add device
		var marker = createMarker(info);
		marker.setMap(mapPanel.getMap());		
		info.marker = marker;
		infoArr.push(info);
	};
	
	function removeTrackerMarker(id){
		for(var i=0, len = infoArr.length; i<len; i++){
			if(id == infoArr[i].deviceid){
				infoArr[i].marker.setMap(null);
				infoArr.splice(i,1);
				return;
			}
		}
	}
	function updatePosition(info){
		for(var i=0, len = infoArr.length; i<len; i++){
			if(info.deviceid == infoArr[i].deviceid){
				infoArr[i].marker.setPosition(info.getPosition());
			}
		}
	}
	function changePos(){
		for(var i=0, len = infoArr.length; i<len; i++){
			var pos = infoArr[i].marker.getPosition();
			var x = pos.lat();
			var y = pos.lng()+0.0001;
			infoArr[i].marker.setPosition(createPoint(x,y));
			//console.log('change '+pos.toString());
		}
	}
	function panTo(point){
		mapPanel.getMap().panTo(point);
	};
	function panToXY(x, y){
		var point = createPoint(x,y);
		panTo(point);
	};
	function panToDevice(deviceId){
		//console.log('pan to '+ deviceId);
		for(var i=0, len = infoArr.length; i<len; i++){
			//console.log(infoArr[i].deviceid);
			if(deviceId == infoArr[i].deviceid){
				panTo(infoArr[i].getPosition());
				
				//console.log('pan to '+ infoArr[i].getPosition().toString());
				return;
			}
		}
	};
	function findLocation(lat, lng, latiCap, longiCap){
		var point = createPoint(lat, lng);
		var title = latiCap+":"+lat;
		title += "\r\n"+longiCap +": "+lng;
		findLocationMarker.setTitle(title);
		findLocationMarker.setPosition(point);
		findLocationMarker.setMap(mapPanel.getMap());
		panTo(point);
	};
	function removeFound(){
		findLocationMarker.setMap(null);
	};
	var directionsDisplay = new google.maps.DirectionsRenderer();
		
	function findDirection(from, to, directionsPanel, language, fnload, fnerror) {
		//console.log('findDirection');
		
		var request = {
			origin : from,
			destination : to,
			travelMode : google.maps.TravelMode.DRIVING
		};
		directionsService.route(request, function (response, status) {
			//console.log('findDirection status: ' + status);
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setMap(mapPanel.getMap());		
				directionsDisplay.setDirections(response);				
				directionsDisplay.setPanel(directionsPanel);
			}else{
				directionsDisplay.setMap(null);		
				fnerror(-1);
			}
		});
		//		directionsDisplay.setMap(map);
	};
	function clearDirection() {
        if (directionsDisplay!= null) {
            directionsDisplay.setMap(null);	
        }
    }
	function createMarker(trackerinfo) {
		var direction = trackerinfo.direction;
		var speedkmh = parseInt(trackerinfo.speed);
		var s = trackerinfo.devicetype;
		var point = trackerinfo.getPosition();
		var imgsrc = "";
		if (trackerinfo.iconname!= null && trackerinfo.iconname != "") {
			imgsrc = "images/trackericon/" + trackerinfo.iconname;
		} else {
			imgsrc = "images/trackericon/" + getDefaultImageUrl(trackerinfo);
		}
		var marker;
		if (trackerinfo.iconname != "") {
			if (direction == "East") {
				imgsrc += "n.png";
			}
			if (direction == "North") {
				imgsrc += "n.png";
			}
			if (direction == "South") {
				imgsrc += "n.png";
			}
			if (direction == "West") {
				imgsrc += "n.png";
			} else {
				imgsrc = ROOT_IMG_URL + "trackericon/" + trackerinfo.iconname;
				imgsrc += ".png";
			}

		}
		if (trackerinfo.gsminfo != null) {
			imgsrc = '/trackericon/' + (trackerinfo.iconname != "" ? trackerinfo.iconname + '.gif' : getDefaultImageUrl(trackerinfo)); //PNG ???,????GIF
			marker = new google.maps.Marker({
					position :point,
					title : 'Click to zoom1'
				});
		} else {
			marker = new google.maps.Marker({
					position : point,
					title : trackerinfo.label,
					icon : imgsrc
				});
		}
		return marker;
	};
	function createPoint(lat, lng) {
			var point = new google.maps.LatLng(lat, lng);
			return point;
	};
	function getDefaultImageUrl(trackerinfo) {
        var s = trackerinfo.devicetype;
        var direction = parseFloat(trackerinfo.direction);
        var url = "blue.gif";

        if (s == 0 || s == 1 || s == 2 || s == 5 || s == 7 || s == 12) {
            url = "man.gif";
        }
        else {
            var baseImagePath;
            if (trackerinfo.gsminfo != null) {
                url = "car.gif";
            }
            else {
                baseImagePath = "car_";
                if (direction >= 337.5 || direction < 22.5)
                    url = baseImagePath + "n.png";
                else if (direction >= 22.5 && direction < 67.5)
                    url = baseImagePath + "ne.png";
                else if (direction >= 67.5 && direction < 112.5)
                    url = baseImagePath + "e.png";
                else if (direction >= 112.5 && direction < 157.5)
                    url = baseImagePath + "se.png";
                else if (direction >= 157.5 && direction < 202.5)
                    url = baseImagePath + "s.png";
                else if (direction >= 202.5 && direction < 247.5)
                    url = baseImagePath + "sw.png";
                else if (direction >= 247.5 && direction < 292.5)
                    url = baseImagePath + "w.png";
                else if (direction >= 292.5 && direction < 337.5)
                    url = baseImagePath + "nw.png";
            }
        }
        return url;
    };
	
	function geoCoder(a, b){
		//ko biet lam gi
	};
	return {
		mapPanel : mapPanel,
		addTrackerMarker : addTrackerMarker,
		removeTrackerMarker:removeTrackerMarker,
		addMultipTrackerMarker:addMultipTrackerMarker,
		removeAllTracker:removeAllTracker,
		changePos:changePos,
		panToDevice: panToDevice,
		updatePosition:updatePosition,
		findLocation:findLocation,
		removeFound:removeFound,
		findDirection:findDirection,
		clearDirection:clearDirection,
		geoCoder:geoCoder
	};
};




// More info at http://github.com/VinylFox/ExtJS.ux.GMapPanel
Ext.ns('Sample');
Sample.ExtGMap = function () {

    var api = null, el = 'ext-map';
    var poly;
    var markers = [];
    var path = new google.maps.MVCArray;
    var _tmplat, _tmplng;
    /**
    * creates an Ext-JS Panel in the 'ext-map' DIV and set its only
    * component to be of the 'gmappanel' type.
    */
    function _init() {
        api = new Ext.ux.GMapPanel({
            xtype: 'gmappanel',
            id: 'my-map',
            gmapType: 'map',
            zoomLevel: 15,
            region: 'center',
            setCenter: {
                lat: 10.788202,
                lng: 106.703228

            },
            listeners: {
                mapready: handleMapReady,
                resize: function () {
                    //console.log(1);
                }
            }
        });

        return api;
    }

    function _initpos(_lat, _lng) {
        _tmplat = _lat;
        _tmplng = _lng;
        api = new Ext.ux.GMapPanel({
            xtype: 'gmappanel',
            id: 'my-map',
            gmapType: 'map',
            zoomLevel: 17,
            region: 'center',
            setCenter: {
                lat: _lat,
                lng: _lng

            },
            listeners: {
                mapready: handleMapWithPos
            }
        });

        return api;
    }

    /**
    * 'mapready' callback handler. localizes returned GMap API
    */
    function handleMapReady(ux, gmap) {
        api = gmap;
        poly = new google.maps.Polygon({
            strokeWeight: 1,
            fillColor: '#5555FF'
        });
        var marker1 = new google.maps.Marker({
            position: new google.maps.LatLng(10.788032914000969, 106.69166564941406),
            map: api,
            draggable: true,
            icon: 'Content/images/trackericon/blue_car_e.png'
        });
        var marker2 = new google.maps.Marker({
            position: new google.maps.LatLng(10.786852519207129, 106.69312477111816),
            map: api,
            draggable: true,
            icon: 'Content/images/trackericon/cam_blanc.png'
        });
        poly.setMap(api);
        poly.setPaths(new google.maps.MVCArray([path]));

        google.maps.event.addListener(api, 'click', addPoint);
        function addPoint(event) {
            //console.log('map: ' + event.latLng);
            path.insertAt(path.length, event.latLng);

            var marker = new google.maps.Marker({
                position: event.latLng,
                map: api,
                draggable: true,
                icon: 'Content/images/poi.gif'
            });
            markers.push(marker);
            marker.setTitle("#" + path.length);

            google.maps.event.addListener(marker, 'click', function () {
                marker.setMap(null);
                for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
                markers.splice(i, 1);
                path.removeAt(i);
            }
			);

            google.maps.event.addListener(marker, 'dragend', function () {
                for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
                path.setAt(i, marker.getPosition());
            }
			);
        }

    }

    function handleMapWithPos(ux, gmap) {
        api = gmap;
        var marker1 = new google.maps.Marker({
            position: new google.maps.LatLng(_tmplat, _tmplng),
            map: api,
            draggable: true,
        });
    }

    // creates a point in geo coordinates
    function createPoint(lat, lng) {
        var point = new google.maps.LatLng(lat, lng);
        return point;
    }

    /**
    * creates a point using the coordinates passed to it and pans
    * the map to that position
    */
    function setLocation(lat, lng) {
        if (Ext.isNumber(lat) && Ext.isNumber(lng)) {
            var point = createPoint(lat, lng);
            api.panTo(point);
        }
    }

    // changes the zoom level
    function zoom(v) {
        if (Ext.isNumber(v)) {
            api.setZoom(v);
        }
    }

    function addMarkerByPosition(lat, lng) {
        api.setCenter(new google.maps.LatLng(lat, lng));
        api.setZoom(17); // Why 17? Because it looks good.

        marker = new google.maps.Marker({
            map: api,
            position: new google.maps.LatLng(lat, lng)
        });
    }

    /**
    * public API.
    * Here we exposed some of the private methods for convenience
    */
    return {
        init: _init,
        location: setLocation,
        zoom: zoom,
        initpos: _initpos
    };


} ();
 
